
"""
Simulated annealing algorithm to solve target allocation problems 
"""

import matplotlib.pyplot as plt
import numpy as np
from targetAlloc import targetalloc


# Mutations
def mut(x):
    p = np.random.randint(0,14)
    x[0,p] = np.random.randint(0,7)
    return x

# print(np.zeros(15,dtype=int))
popNum = 1

# Initialization the group
# Generate a random matrix in the range of value
x_0 = np.random.randint(0,7,size=(popNum,15))

# Calculate the fitness
y_0 = targetalloc(x_0)

max_x = x_0
max_y = y_0

# Parameter initialization
# The initial temperature
T0 = 100
# The maximum number of iterations
maxgen = 100
# The number of algorithm iterations at the same temperature
Lk = 200
# Cooling coefficient
alfa = 0.95


bestFit = []
for g in range(0,maxgen):
    for iter in range(0,Lk):
        # New solution
        x_new = mut(x_0)

        # Computing new solution adaptivity value
        y_new = targetalloc(x_new)

        if y_new > max_y:
            x_0 = x_new
            y_0 = y_new
        else:
            c = np.random.rand()
            # Calculate reception probability
            pro = np.exp(-(max_y-y_new)/T0)
            if c <= pro:
                x_0 = x_new
                y_0 = y_new
        
        if y_0 > max_y:
            max_y = y_0
            max_x = x_0

    bestFit.append(max_y)
    T0 = T0*alfa

print(type(bestFit))


# Drawing
plt.style.use('ggplot')
fig = plt.figure()
ax = fig.add_subplot(111)

plt.ylabel('Fitness', fontdict={'family' : 'Times New Roman', 'size'   : 16})
plt.xlabel('Evolutionary generation', fontdict={'family' : 'Times New Roman', 'size'   : 16})
plt.yticks(fontproperties = 'Times New Roman', size = 14)
plt.xticks(fontproperties = 'Times New Roman', size = 14)
plt.legend(prop={'family' : 'Times New Roman', 'size'   : 16})

plt.plot(bestFit)
plt.show()
